//
//  XX_XXXPushManager.swift
//  测试
//
//  Created by 夏雨薇 on 2019/7/9.
//  Copyright © 2019 ceshi. All rights reserved.
//

import UIKit


class XX_XXXPushManager: NSObject {
    
    /// 极光Key值
    let XX_XXX_JPushKey: String = "1a5782a1b69e38a18cd97276"
    
    static let shareInsance = XX_XXXPushManager()
    
    /// 注册极光推送
    ///
    /// - Parameters:
    ///   - jpushKey: 极光推送Key
    ///   - channel: 发布渠道(默认为 app store)
    ///   - launchOptions: <#launchOptions description#>
    func XX_XXXreigisterJPush(launchOptions: [UIApplication.LaunchOptionsKey: Any]?, delegate: JPUSHRegisterDelegate){
        //Push根据版本设置不同的推送
        if #available(iOS 10.0, *){
            let entiity = JPUSHRegisterEntity()
            entiity.types = Int(UNAuthorizationOptions.alert.rawValue |
                UNAuthorizationOptions.badge.rawValue |
                UNAuthorizationOptions.sound.rawValue)
            JPUSHService.register(forRemoteNotificationConfig: entiity, delegate: delegate)
        }
        else if #available(iOS 8.0, *) {
            let types = UIUserNotificationType.badge.rawValue |
                UIUserNotificationType.sound.rawValue |
                UIUserNotificationType.alert.rawValue
            JPUSHService.register(forRemoteNotificationTypes: types, categories: nil)
        }
        else {
            let type = UIRemoteNotificationType.badge.rawValue |
                UIRemoteNotificationType.sound.rawValue |
                UIRemoteNotificationType.alert.rawValue
            JPUSHService.register(forRemoteNotificationTypes: type, categories: nil)
        }
        
        // 根据环境的不同,设置不同的apsForProduction值
        JPUSHService.setup(withOption: launchOptions, appKey: XX_XXX_JPushKey, channel: "App Store", apsForProduction: true)
    }
    
}

//MARK: - JPUSHRegisterDelegate
extension AppDelegate: JPUSHRegisterDelegate {
    
    //-MARK:设置极光推送相关代理
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        
        let userInfo = notification.request.content.userInfo
        if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!{
            JPUSHService.handleRemoteNotification(userInfo)
        }
        // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
        completionHandler(Int(UNAuthorizationOptions.alert.rawValue))
    }
    
    //设置推送服务
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        let userInfo = response.notification.request.content.userInfo
        if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!{
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler()
    }
    
    @available(iOS 12.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, openSettingsFor notification: UNNotification?) {
        if (notification != nil) && (notification?.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
            //从通知界面直接进入应用
        }
        else{
            //从通知设置界面进入应用
        }
    }
}


//MARK: - 推送相关设置
extension AppDelegate {
    //注册推送
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
    }
    
    //取消推送相关通知
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        JPUSHService.handleRemoteNotification(userInfo)
        completionHandler(.newData)
    }
    
    //设置推送BadgeNumber
    func applicationDidEnterBackground(_ application: UIApplication) {
        application.applicationIconBadgeNumber = 0
        if #available(iOS 10.0, *) {
            // To remove all delivered notifications
            UNUserNotificationCenter.current().removeAllDeliveredNotifications()
            // To remove all pending notififcations which are not delivered yet but scheduled.
            UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        } else {
            // Fallback on earlier versions
            application.cancelAllLocalNotifications()
        }
    }
    
    //设置推送BadgeNumber
    func applicationWillEnterForeground(_ application: UIApplication) {
        UIApplication.shared.applicationIconBadgeNumber = 0
        if #available(iOS 10.0, *) {
            // To remove all delivered notifications
            UNUserNotificationCenter.current().removeAllDeliveredNotifications()
            // To remove all pending notifications which are not delivered yet but scheduled.
            UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        } else {
            // Fallback on earlier versions
            application.cancelAllLocalNotifications()
        }
    }
    
    /// 刚进入程序是检查网络是否可用
    func applicationDidBecomeActive(_ application: UIApplication) {
        UIApplication.shared.applicationIconBadgeNumber = 0
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        JPUSHService.handleRemoteNotification(userInfo)
    }
    
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        if application.keyWindow?.tag == Int(6666) {
            return UIInterfaceOrientationMask.all
        }else{
            return UIInterfaceOrientationMask.portrait
        }
    }
}
